<template>
  <div class="admission-register">
    <div class="header-row">
      <h2>入院登记</h2>
      <div class="btn-group">
        <button class="btn primary" @click="handleSave" :disabled="loading">
          {{ loading ? '保存中...' : '暂存' }}
        </button>
        <button class="btn" @click="handleSubmit" :disabled="loading">
          {{ loading ? '提交中...' : '提交' }}
        </button>
        <button class="btn secondary" @click="resetForm" :disabled="loading">重置</button>
      </div>
    </div>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="90px" class="form-block">
      <div class="section-title">
        <span class="section-bar"></span>
        <span>基本信息</span>
        <div class="section-divider"></div>
      </div>
      <div class="form-card">
        <div class="form-row">
          <div class="form-item required">
            <label class="form-label">住院号</label>
            <input 
              v-model="form.hospitalNumber" 
              class="form-input" 
              :class="{ 'has-error': errors.hospitalNumber }"
              placeholder="请输入住院号" 
            />
            <span v-if="errors.hospitalNumber" class="error-msg">{{ errors.hospitalNumber }}</span>
          </div>
          <div class="form-item required">
            <label class="form-label">姓名</label>
            <input 
              v-model="form.name" 
              class="form-input" 
              :class="{ 'has-error': errors.name }"
              placeholder="请输入姓名" 
            />
            <span v-if="errors.name" class="error-msg">{{ errors.name }}</span>
          </div>
          <div class="form-item required">
            <label class="form-label">身份证号</label>
            <input 
              v-model="form.idCard" 
              class="form-input" 
              :class="{ 'has-error': errors.idCard }"
              placeholder="请输入身份证号" 
              @blur="handleIdCardChange"
            />
            <span v-if="errors.idCard" class="error-msg">{{ errors.idCard }}</span>
          </div>
          <div class="form-item required">
            <label class="form-label">年龄</label>
            <div class="age-input-wrap">
              <input 
                v-model="form.age" 
                type="number" 
                min="0" 
                max="120" 
                class="form-input" 
                :class="{ 'has-error': errors.age }"
                placeholder="请输入年龄" 
              />
              <span class="suffix">岁</span>
            </div>
            <span v-if="errors.age" class="error-msg">{{ errors.age }}</span>
          </div>
          <div class="form-item required">
            <label class="form-label">出生日期</label>
            <input 
              v-model="form.birthDate" 
              type="date" 
              class="form-input" 
              :class="{ 'has-error': errors.birthDate }"
              placeholder="请选择出生日期" 
            />
            <span v-if="errors.birthDate" class="error-msg">{{ errors.birthDate }}</span>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item required">
            <label class="form-label">性别</label>
            <select 
              v-model="form.gender" 
              class="form-input"
              :class="{ 'has-error': errors.gender }"
            >
              <option value="">请选择性别</option>
              <option value="男">男</option>
              <option value="女">女</option>
            </select>
            <span v-if="errors.gender" class="error-msg">{{ errors.gender }}</span>
          </div>
          <div class="form-item">
            <label class="form-label">家庭住址</label>
            <input v-model="form.address" class="form-input" placeholder="请输入家庭住址(可选)" />
          </div>
        </div>
      </div>
      <div class="section-title">
        <span class="section-bar"></span>
        <span>医保信息</span>
        <div class="section-divider"></div>
      </div>
      <div class="form-card">
        <div class="form-row">
          <div class="form-item required">
            <label class="form-label">支付类型</label>
            <select v-model="form.paymentType" class="form-input">
              <option value="医保">医保</option>
              <option value="自费">自费</option>
            </select>
            <span v-if="errors.paymentType" class="error-msg">{{ errors.paymentType }}</span>
          </div>
          <div class="form-item" v-if="form.paymentType === '医保'">
            <label class="form-label">医保人员类型</label>
            <select v-model="form.personCategory" class="form-input">
              <option value="在职">在职</option>
              <option value="退休">退休</option>
            </select>
          </div>
          <div class="form-item">
            <label class="form-label">医院等级</label>
            <select v-model="form.hospitalLevel" class="form-input">
              <option value="三">三级</option>
              <option value="二">二级</option>
              <option value="一">一级</option>
            </select>
          </div>
          <div class="form-item">
            <label class="form-label">入院时间</label>
            <input v-model="form.admissionTime" type="datetime-local" class="form-input" placeholder="请选择入院时间" />
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { addInsuredPerson } from '@/api/admission'
import 'element-plus/dist/index.css'

const form = reactive({
  hospitalNumber: '', // 住院号
  name: '',
  idCard: '', // 身份证号
  age: '',
  birthDate: '', // 出生日期
  gender: '', // 性别
  address: '', // 家庭住址
  paymentType: '医保', // 支付类型（自费/医保）
  personCategory: '在职', // 医保人员类型（在职/退休）
  hospitalLevel: '三', // 医院等级（三/二/一）
  admissionTime: '' // 入院时间
})

const loading = ref(false)
const errors = reactive({})
const savedData = ref(null) // 用于暂存数据

// 表单验证
function validate() {
  errors.hospitalNumber = form.hospitalNumber ? '' : '住院号不能为空'
  errors.name = form.name ? '' : '姓名不能为空'
  errors.idCard = form.idCard ? '' : '身份证号不能为空'
  errors.age = form.age ? '' : '年龄不能为空'
  errors.birthDate = form.birthDate ? '' : '出生日期不能为空'
  errors.gender = form.gender ? '' : '性别不能为空'
  errors.paymentType = form.paymentType ? '' : '支付类型不能为空'
  
  // 身份证号格式验证
  if (form.idCard && !/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(form.idCard)) {
    errors.idCard = '身份证号格式不正确'
  }
  
  // 年龄验证
  if (form.age && (form.age < 0 || form.age > 120)) {
    errors.age = '年龄必须在0-120之间'
  }
  
  return !Object.values(errors).some(Boolean)
}

// 根据身份证号自动计算年龄和出生日期
function handleIdCardChange() {
  if (form.idCard && form.idCard.length >= 14) {
    try {
      const year = parseInt(form.idCard.substring(6, 10))
      const month = parseInt(form.idCard.substring(10, 12))
      const day = parseInt(form.idCard.substring(12, 14))
      
      const birthDate = new Date(year, month - 1, day)
      const today = new Date()
      
      // 计算年龄
      let age = today.getFullYear() - year
      const monthDiff = today.getMonth() - (month - 1)
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < day)) {
        age--
      }
      
      form.age = age
      form.birthDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
    } catch (error) {
      console.error('身份证号解析错误:', error)
    }
  }
}

// 暂存功能 - 本地保存，不与数据库交互
function handleSave() {
  // 暂存不需要完整验证，只验证基本格式
  const basicErrors = {}
  
  // 只验证已填写字段的格式
  if (form.idCard && !/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(form.idCard)) {
    basicErrors.idCard = '身份证号格式不正确'
  }
  
  if (form.age && (form.age < 0 || form.age > 120)) {
    basicErrors.age = '年龄必须在0-120之间'
  }
  
  if (Object.values(basicErrors).some(Boolean)) {
    // 更新错误状态
    Object.keys(errors).forEach(key => {
      errors[key] = basicErrors[key] || ''
    })
    ElMessage.error('请检查填写格式')
    return
  }
  
  // 清空错误状态
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })
  
  // 本地暂存数据
  savedData.value = { ...form }
  localStorage.setItem('admission_draft', JSON.stringify(form))
  
  ElMessage.success('暂存成功！数据已保存到本地')
}

// 提交功能 - 正式提交到数据库
async function handleSubmit() {
  if (!validate()) {
    ElMessage.error('请填写完整的必填信息')
    return
  }
  
  loading.value = true
  try {
    const requestData = {
      ...form,
      birthDate: form.birthDate ? new Date(form.birthDate).toISOString() : null
    }
    
    // 不传入patientId，让数据库自增生成
    delete requestData.patientId
    
    const response = await addInsuredPerson(requestData)
    
    if (response.flag) {
      ElMessage.success('入院登记成功！')
      // 清除暂存数据
      localStorage.removeItem('admission_draft')
      savedData.value = null
      // 可以在这里添加跳转逻辑
      // resetForm()
    } else {
      ElMessage.error(response.message || '提交失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 重置表单
function resetForm() {
  Object.keys(form).forEach(key => {
    if (key === 'paymentType') {
      form[key] = '医保'
    } else if (key === 'personCategory') {
      form[key] = '在职'
    } else if (key === 'hospitalLevel') {
      form[key] = '三'
    } else {
      form[key] = ''
    }
  })
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })
  
  // 清除暂存数据
  localStorage.removeItem('admission_draft')
  savedData.value = null
  
  ElMessage.success('表单已重置')
}

// 页面加载时恢复暂存数据
function loadDraftData() {
  try {
    const draftData = localStorage.getItem('admission_draft')
    if (draftData) {
      const parsedData = JSON.parse(draftData)
      Object.keys(parsedData).forEach(key => {
        if (form.hasOwnProperty(key)) {
          form[key] = parsedData[key]
        }
      })
      savedData.value = parsedData
      ElMessage.info('已恢复上次暂存的数据')
    }
  } catch (error) {
    console.error('恢复暂存数据失败:', error)
    localStorage.removeItem('admission_draft')
  }
}

// 组件挂载时恢复数据
onMounted(() => {
  loadDraftData()
})
</script>

<style scoped>
.admission-register {
  background: #f7f8fa;
  border-radius: 16px;
  margin: 32px 0 0 0;
  padding: 40px 0 40px 0;
  min-width: 0;
  box-shadow: 0 2px 12px rgba(0,0,0,0.04);
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}
.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
  padding: 0 48px;
}
.header-row h2 {
  font-size: 25px;
  font-weight: 700;
  color: #34495e;
  margin: 0;
}
.btn-group {
  display: flex;
  gap: 28px;
}
.btn {
  padding: 12px 40px;
  border-radius: 10px;
  border: none;
  font-size: 18px;
  font-weight: 500;
  background: #f5f6fa;
  color: #34495e;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s, transform 0.2s;
  box-shadow: 0 2px 8px rgba(64,158,255,0.06);
}
.btn.primary {
  background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
  color: #fff;
  box-shadow: 0 4px 16px rgba(64,158,255,0.13);
}
.btn.secondary {
  background: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}
.btn.secondary:hover {
  background: #ecf5ff;
  color: #409eff;
  border-color: #c6e2ff;
}
.btn:hover {
  background: #e0e6f6;
  transform: translateY(-2px) scale(1.03);
  box-shadow: 0 6px 18px rgba(64,158,255,0.10);
}
.btn.primary:hover {
  background: linear-gradient(90deg, #3076c9 0%, #409eff 100%);
}
.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}
.btn:disabled:hover {
  transform: none;
  background: inherit;
}
.form-block {
  margin-top: 12px;
  padding: 0 48px;
}
.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
  color: #34495e;
  margin: 38px 0 18px 0;
  letter-spacing: 1px;
}
.section-bar {
  width: 4px;
  height: 22px;
  background: #409eff;
  border-radius: 2px;
  margin-right: 12px;
  display: inline-block;
}
.section-title .section-divider {
  flex: 1;
  height: 1px;
  background: #e5e6eb;
  margin-left: 18px;
  border-radius: 1px;
}
.form-card {
  background: #fafbfc;
  border-radius: 10px;
  box-shadow: none;
  border: 1px solid #f0f0f0;
  padding: 28px 28px 10px 28px;
  margin-bottom: 8px;
}
.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 32px 36px;
  align-items: flex-end;
}
.age-birth-row {
  display: flex;
  align-items: flex-end;
  gap: 36px;
  margin-bottom: 18px;
}
.age-item {
  flex: 0 0 180px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
.birth-item {
  flex: 0 0 260px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  /* 保证与年龄输入框基线对齐 */
}
.age-input-wrap {
  display: flex;
  align-items: center;
  height: 48px;
}
.age-item input {
  width: 180px !important;
  margin-right: 4px;
  text-align: left;
  height: 48px;
  border-radius: 9px;
  border: 1.5px solid #dbe2ea;
  font-size: 16px;
  background: #f8fafc;
  transition: border 0.2s, box-shadow 0.2s;
  padding: 14px 18px;
  box-sizing: border-box;
  line-height: 20px;
  color: #222;
}
.age-item input:focus {
  border: 1.5px solid #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}
.suffix {
  color: #888;
  font-size: 15px;
  margin: 0;
  height: 48px;
  display: flex;
  align-items: center;
  line-height: 20px;
}
.birth-item input[type='date'] {
  height: 48px;
  border-radius: 9px;
  border: 1.5px solid #dbe2ea;
  font-size: 16px;
  background: #f8fafc;
  padding: 14px 18px;
  transition: border 0.2s, box-shadow 0.2s;
}
.birth-item input[type='date']:focus {
  border: 1.5px solid #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}
.age-input-long {
  width: 180px !important;
}
@media (max-width: 1200px) {
  .form-row {
    gap: 18px 0;
  }
  .form-item {
    min-width: 160px;
    max-width: 100%;
  }
}
.form-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1 1 200px;
  max-width: 320px;
  margin-bottom: 0;
  position: relative;
  justify-content: flex-end;
}
.form-item label {
  font-size: 15px;
  color: #34495e;
  margin-bottom: 8px;
  font-weight: 500;
  display: flex;
  align-items: center;
}
.form-item.required label::after {
  content: '*';
  color: #e74c3c;
  margin-left: 4px;
  font-size: 15px;
}
.form-item input,
.form-item select {
  height: 48px;
  border-radius: 9px;
  border: 1.5px solid #bfcbd9;
  background: #f8fafc;
  font-size: 16px;
  color: #222;
  padding: 14px 18px;
  box-sizing: border-box;
  outline: none;
  transition: border 0.2s, box-shadow 0.2s;
  width: 100%;
}
.form-item input:focus,
.form-item select:focus {
  border: 1.5px solid #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}
.form-item input::placeholder {
  color: #bfcbd9;
  opacity: 1;
}
.form-item select,
.form-item input[type='date'],
.form-item input[type='datetime-local'] {
  height: 48px;
  border-radius: 9px;
  border: 1.5px solid #bfcbd9;
  background: #f8fafc;
  font-size: 16px;
  color: #222;
  padding: 14px 18px;
  box-sizing: border-box;
  outline: none;
  transition: border 0.2s, box-shadow 0.2s;
  width: 100%;
}
.select-wrap {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
}
.select-wrap select {
  width: 100%;
  min-width: 0;
  appearance: none;
  -webkit-appearance: none;
  background: transparent;
  padding: 14px 38px 14px 18px; /* 右侧留空间给箭头，左侧与input一致 */
  border: 1.5px solid #dbe2ea;
  border-radius: 12px;
  font-size: 17px;
  height: 48px;
  color: #222;
  transition: border 0.2s, box-shadow 0.2s;
  box-shadow: 0 2px 8px rgba(64,158,255,0.04);
  outline: none;
  cursor: pointer;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  line-height: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-sizing: border-box;
}
.select-wrap select:focus {
  border: 1.5px solid #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}
.select-wrap select option {
  color: #222;
  background: #fff;
  font-size: 16px;
  border-radius: 8px;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  padding: 10px 18px;
  transition: background 0.2s, color 0.2s;
}
.select-wrap select option:checked,
.select-wrap select option:focus {
  background: #eaf4ff !important;
  color: #409eff;
}
/* 下拉菜单弹窗美化（仅部分浏览器支持） */
select::-webkit-scrollbar {
  width: 8px;
  background: #f0f4fa;
  border-radius: 8px;
}
select::-webkit-scrollbar-thumb {
  background: #eaf4ff;
  border-radius: 8px;
}
.select-wrap select:hover {
  box-shadow: 0 4px 16px rgba(64,158,255,0.10);
}
.select-arrow {
  position: absolute;
  right: 14px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 7px solid #bfcbd9;
  transition: border-top-color 0.2s;
}
.select-wrap select:focus + .select-arrow {
  border-top-color: #409eff;
}
.form-item.has-error input,
.form-item.has-error select {
  border: 1.5px solid #f56c6c !important;
  box-shadow: 0 0 0 2px #fef0f0 !important;
}
.error-msg {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  display: block;
  line-height: 1.4;
}
.fade-in-enter-active, .fade-in-leave-active {
  transition: opacity 0.3s;
}
.fade-in-enter-from, .fade-in-leave-to {
  opacity: 0;
}
/* 覆盖 Element Plus 日期选择器输入框样式 */
:deep(.custom-date-picker .el-input__wrapper) {
  border-radius: 9px;
  border: 1.5px solid #dbe2ea;
  background: #f8fafc;
  min-height: 48px;
  box-shadow: none;
  padding: 0 0;
  transition: border 0.2s, box-shadow 0.2s;
}
:deep(.custom-date-picker .el-input__wrapper.is-focus) {
  border: 1.5px solid #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}
:deep(.custom-date-picker .el-input__inner) {
  height: 48px;
  font-size: 16px;
  background: #f8fafc;
  color: #222;
  border-radius: 9px;
  padding: 0 18px;
  box-sizing: border-box;
}
:deep(.custom-date-picker .el-input__inner::placeholder) {
  color: #bfcbd9;
  opacity: 1;
}
/* 让 el-date-picker 框和 el-input 完全一致 */
:deep(.custom-date-picker.custom-input .el-input__wrapper),
:deep(.custom-date-picker.custom-input .el-input__inner),
:deep(.custom-input .el-input__wrapper),
:deep(.custom-input .el-input__inner) {
  height: 48px !important;
  min-height: 48px !important;
  border-radius: 9px !important;
  border: 1.5px solid #dbe2ea !important;
  background: #f8fafc !important;
  font-size: 16px !important;
  color: #222 !important;
  padding: 14px 18px !important;
  box-sizing: border-box !important;
  box-shadow: none !important;
  transition: border 0.2s, box-shadow 0.2s;
  line-height: 20px !important;
  display: flex !important;
  align-items: center !important;
}
:deep(.custom-date-picker.custom-input .el-input__wrapper.is-focus),
:deep(.custom-input .el-input__wrapper.is-focus) {
  border: 1.5px solid #409eff !important;
  box-shadow: 0 0 0 2px #eaf4ff !important;
}
:deep(.custom-date-picker.custom-input .el-input__inner::placeholder),
:deep(.custom-input .el-input__inner::placeholder) {
  color: #bfcbd9 !important;
  opacity: 1 !important;
}
:deep(.custom-date-picker.custom-input .el-input__suffix),
:deep(.custom-date-picker.custom-input .el-input__prefix),
:deep(.custom-input .el-input__suffix),
:deep(.custom-input .el-input__prefix) {
  height: 48px !important;
  display: flex !important;
  align-items: center !important;
}
:deep(.custom-date-picker.custom-input .el-input__icon),
:deep(.custom-input .el-input__icon) {
  font-size: 18px !important;
  color: #bfcbd9 !important;
  margin-right: 8px !important;
}
/* el-select 下拉弹窗美化 */
:deep(.el-select-dropdown) {
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(64,158,255,0.13) !important;
  border: 1.5px solid #eaf4ff !important;
  padding: 6px 0 !important;
}
:deep(.el-select-dropdown__item) {
  font-size: 16px !important;
  border-radius: 8px !important;
  padding: 10px 18px !important;
  color: #222 !important;
  transition: background 0.2s, color 0.2s;
}
:deep(.el-select-dropdown__item.selected),
:deep(.el-select-dropdown__item.hover) {
  background: #eaf4ff !important;
  color: #409eff !important;
}
/* 统一所有 Element Plus 表单控件的外观和边框色 */
:deep(.custom-input .el-input__wrapper) {
  height: 48px !important;
  min-height: 48px !important;
  border-radius: 9px !important;
  border: 1.5px solid #bfcbd9 !important;
  background: #f8fafc !important;
  box-shadow: none !important;
  padding: 0 !important;
  display: flex !important;
  align-items: center !important;
  transition: border 0.2s, box-shadow 0.2s;
}
:deep(.custom-input .el-input__wrapper.is-focus),
:deep(.custom-input .el-input__wrapper:hover) {
  border: 1.5px solid #409eff !important;
  box-shadow: 0 0 0 2px #eaf4ff !important;
}
:deep(.custom-input .el-input__inner) {
  height: 48px !important;
  min-height: 48px !important;
  border-radius: 9px !important;
  background: #f8fafc !important;
  font-size: 16px !important;
  color: #222 !important;
  padding: 14px 18px !important;
  box-sizing: border-box !important;
  border: none !important;
  line-height: 20px !important;
  outline: none !important;
  box-shadow: none !important;
  display: flex !important;
  align-items: center !important;
}
:deep(.custom-input .el-input__inner::placeholder) {
  color: #bfcbd9 !important;
  opacity: 1 !important;
}
:deep(.custom-input .el-input__suffix),
:deep(.custom-input .el-input__prefix) {
  height: 48px !important;
  display: flex !important;
  align-items: center !important;
}
:deep(.custom-input .el-input__icon) {
  font-size: 18px !important;
  color: #bfcbd9 !important;
  margin-right: 8px !important;
}
/* 让 el-select 的下拉箭头和内容区与 el-input 完全一致 */
:deep(.custom-input .el-select .el-input__suffix) {
  height: 48px !important;
  display: flex !important;
  align-items: center !important;
  color: #bfcbd9 !important;
}
:deep(.custom-input .el-select .el-input__icon) {
  font-size: 18px !important;
  color: #bfcbd9 !important;
  margin-right: 8px !important;
}
:deep(.custom-input .el-select .el-input__inner) {
  padding-right: 32px !important;
}
/* 单位“岁”对齐 */
.suffix {
  color: #888;
  font-size: 15px;
  margin: 0;
  height: 48px;
  display: flex;
  align-items: center;
  line-height: 20px;
}
/* 优化原生 select 下拉弹窗样式 */
</style>